<template>
  <div class="table-container">
    <vab-query-form>
      <!-- <vab-query-form-left-panel>
        <el-button icon="el-icon-delete" type="danger" @click="handleAnyDelete">删除</el-button>
      </vab-query-form-left-panel>-->
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
          <div class="left-panel">
            <el-button icon="el-icon-delete" type="danger" @click="handleAnyDelete">删除</el-button>
          </div>
        </el-col>
        <el-col :xs="22" :sm="22" :md="22" :lg="22" :xl="22">
          <div class="right-panel">
            <el-select
              v-if="user.level <= 1"
              v-model="queryForm.logActor"
              placeholder="日志对象"
              @change="actorChange"
              class="mr-5px"
            >
              <el-option label="村民" value="0" />
              <el-option label="管理员" value="1" />
            </el-select>

            <el-date-picker
              v-model="queryForm.dataTimeRange"
              type="datetimerange"
              :picker-options="pickerOptions2"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              class="mr-5px"
              @change="changeDataTimeRange"
            ></el-date-picker>

            <el-select
              v-if="user.level <= 1"
              v-model="queryForm.logType"
              multiple
              placeholder="类型筛选"
              clearable
              @change="typeChange"
              class="mr-5px"
            >
              <el-option
                v-for="type in logTypeAtt"
                :key="type.value"
                :label="type.name"
                :value="type.value"
              />
            </el-select>

            <el-cascader
              v-if="user.level <= 1"
              :options="townToVillage"
              :props="townToVillProp"
              placeholder="地区筛选"
              change-on-select
              clearable
              @change="townToVillageChange"
            />
            <el-cascader
              v-if="user.level == 2"
              :options="townToVillage"
              :props="townToVillProp"
              placeholder="地区筛选"
              change-on-select
              clearable
              @change="villageToTypeChange"
            />

            <el-form ref="form" :model="queryForm" :inline="true" @submit.native.prevent>
              <el-form-item>
                <el-input v-model="queryForm.keyword" placeholder="查询内容或字段" clearable />
              </el-form-item>
              <el-form-item>
                <el-button
                  icon="el-icon-search"
                  type="primary"
                  native-type="submit"
                  @click="handleQuery"
                >查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-col>
      <vab-query-form-left-panel :span="24"></vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      :row-class-name="tableRowClassName"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="95">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="user.username" label="管理员" sortable="custom" />
      <el-table-column prop="user.level" label="管理员等级" sortable="custom">
        <template slot-scope="scope">{{ scope.row.user.level | getLevelMes }}</template>
      </el-table-column>

      <el-table-column prop="handleName" label="操作信息" />
      <el-table-column prop="createdAt" label="操作时间" sortable="custom">
        <template slot-scope="scope">{{ scope.row.createdAt | datatime }}</template>
      </el-table-column>
      <el-table-column prop="handleStatus" label="类型" sortable="custom">
        <template slot-scope="scope">{{ scope.row.handleStatus | handleStatus }}</template>
      </el-table-column>
      <el-table-column prop="handleMoudle" label="操作模块" sortable="custom">
        <template slot-scope="scope">{{ scope.row.handleMoudle | handleMoudle }}</template>
      </el-table-column>
      <el-table-column v-if="user.level <= 0" label="操作" width="180px" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "MyTable",
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  filters: {
    handleStatus(status) {
      let statusMap = {
        log: "信息浏览",
        warn: "需要关注",
        error: "敏感操作",
        info: "新增数据",
        data: "批量新增",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      list: [],
      listLoading: false,
      layout: "total, sizes, prev, pager, next, jumper",
      total: 0,
      background: true,
      selectRows: "",
      elementLoadingText: "正在加载...",
      queryForm: {
        pageNo: 1,
        pageSize: 20,
        town: "",
        village: "",
        keyword: "",
        logType: ["error", "data"],
        dataTimeRange: "",
        logActor: "1",
      },

      // excle 导出
      filename: "补助项信息",
      autoWidth: true,
      bookType: "xlsx",
      options: ["xlsx", "csv", "txt"],

      table: {},
      selectedData: {},
      sort: [],

      // 搜索
      townToVillProp: {
        value: "id",
        label: "name",
        children: "village",
      },
      townToVillage: [],
      queryVillageAtt: [],

      logTypeAtt: [
        {
          name: "查询检索",
          value: "log",
        },
        {
          name: "删除数据",
          value: "error",
        },
        {
          name: "修改数据",
          value: "warn",
        },
        {
          name: "批量上传",
          value: "data",
        },
        {
          name: "新增数据",
          value: "info",
        },
      ],
      pickerOptions2: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.init();
    this.fetchData();
  },
  beforeDestroy() {},
  mounted() {},
  methods: {
    tableRowClassName({ row }) {
      if (row.handleStatus == "log") {
        return "log-row";
      }
      if (row.handleStatus == "error") {
        return "error-row";
      }
      if (row.handleStatus == "warn") {
        return "warn-row";
      }
      if (row.handleStatus == "info") {
        return "info-row";
      }
      if (row.handleStatus == "data") {
        return "data-row";
      }
    },
    tableSortChange(column) {
      // const imageList = [];
      // this.$refs.tableSort.tableData.forEach((item, index) => {
      //   imageList.push(item.img);
      // });
      if (column.order) {
        this.sort = [
          `${column.prop},${column.order == "descending" ? "DESC" : "ASC"}`,
        ];
      } else {
        this.sort = [];
      }
      this.fetchData();
    },
    setSelectRows(val) {
      this.selectRows = val;
      this.selectedData = this.transformData(val);
    },
    handleDelete(id) {
      this.$baseConfirm("你确定要删除当前项吗", null, async () => {
        await this.delete(id);
      });
    },
    handleAnyDelete() {
      if (this.selectRows.length > 0) {
        const att = JSON.parse(JSON.stringify(this.selectRows));
        this.$baseConfirm("你确定要删除选中项吗", null, () => {
          att.forEach(async (item) => {
            await this.delete(item.id);
          });
        });
      } else {
        this.$baseMessage("未选中任何行", "error");
      }
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val;
      this.fetchData();
    },
    handleQuery() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    getQuery() {
      let query = JSON.parse(JSON.stringify(this.queryForm));
      let logTypeAtt = this.logTypeAtt;
      let fields = "";
      let user = this.user;
      let s = {
        init() {
          if (query.logActor == "1") {
            this["actor"] = "1"
            this["user.level"] =  {
              $in: ["-2", "-1", "0", "1", "2", "3"].filter(
                (v) => v > user.level
              ),
            }
            if (query.village) {
              if (Array.isArray(query.village) && query.village.length > 0) {
                this["user.village.id"] = {
                  $in: query.village,
                };
              } else if (!Array.isArray(query.village)) {
                this["user.village.id"] = {
                  $eq: query.village,
                };
              }
            }
            if (query.town) {
              this["user.town.id"] = {
                $eq: query.town,
              };
            }
            if (query.logType.length > 0) {
              this["handleStatus"] = {
                $in: query.logType,
              };
            } else if (query.logType.length == 0) {
              let att = [];
              logTypeAtt.forEach((logType) => att.push(logType.value));
              this["handleStatus"] = {
                $in: att,
              };
            }
            if (query.dataTimeRange.length > 0) {
              this["createdAt"] = {
                $between: query.dataTimeRange,
              };
            }
            this["$or"] = [
              {
                "user.name": {
                  $cont: query.keyword,
                },
              },
              {
                "user.username": {
                  $cont: query.keyword,
                },
              },
            ];
          } else if (query.logActor == "0") {
            if (query.village) {
              if (Array.isArray(query.village) && query.village.length > 0) {
                this["villager.village.id"] = {
                  $in: query.village,
                };
              } else if (!Array.isArray(query.village)) {
                this["villager.village.id"] = {
                  $eq: query.village,
                };
              }
            }
            if (query.town) {
              this["villager.village.town.id"] = {
                $eq: query.town,
              };
            }
            if (query.logType.length > 0) {
              this["handleStatus"] = {
                $in: query.logType,
              };
            } else if (query.logType.length == 0) {
              let att = [];
              logTypeAtt.forEach((logType) => att.push(logType.value));
              this["handleStatus"] = {
                $in: att,
              };
            }
            if (query.dataTimeRange.length > 0) {
              this["createdAt"] = {
                $between: query.dataTimeRange,
              };
            }

            this["$or"] = [
              {
                "user.name": {
                  $cont: query.keyword,
                },
              },
              {
                "user.username": {
                  $cont: query.keyword,
                },
              },
            ];
          }

          return this;
        },
      };

      let or = "";
      let sort = `${this.sort.map((item) => `sort=${item}`).join("&")}`;
      let join = `join=user&join=user.area&join=user.village&join=user.town`;
      let pageInfo = `limit=${query.pageSize}&page=${query.pageNo}`;

      //列排序 列名 排序规则 ASC(递增),DESC(递降)
      //粗略搜索
      // let search = ''
      return `s=${JSON.stringify(
        s.init()
      )}&or=${or}&${sort}&${join}&${pageInfo}`;
      // return `${join}&${pageInfo}`
    },
    async fetchData() {
      console.log(this.user);
      this.listLoading = true;
      let res = await this.$http.get("logger" + `?${this.getQuery()}`);
      this.list = res.data.data;
      this.total = res.data.total;
      this.listLoading = false;
      this.table = this.transformData(this.list);
      console.log(this.table);
    },

    async delete(id) {
      const res = await this.$http.delete(`logger/${id}`);
      if (res.status == 200) {
        this.$baseMessage("删除成功", "success");
        this.fetchData();
      } else {
        this.$baseMessage("删除失败", "error");
      }
    },

    transformData(objectData) {
      let header = [];
      let data = [];
      if (objectData.length > 0) {
        for (const key in objectData[0]) {
          header.push(key);
        }
        objectData.forEach((item) => {
          let att = [];
          header.forEach((key) => att.push(item[key]));
          data.push(att);
        });
      }
      return {
        header,
        data,
      };
    },
    //excel 导出
    allHandleDownload() {
      import("@/vendor/ExportExcel").then((excel) => {
        const { header, data } = this.table;
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType,
        });
      });
    },
    partHandleDownload() {
      if (
        Array.isArray(this.selectedData.data) &&
        this.selectedData.data.length > 0
      ) {
        import("@/vendor/ExportExcel").then((excel) => {
          const { header, data } = this.selectedData;
          excel.export_json_to_excel({
            header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType,
          });
        });
      } else {
        this.$baseMessage("请至少选择一行", "error");
      }
    },

    async init() {
      this.setQuery();
      if (this.user.level <= 1) {
        const res = await this.$http.get(
          `town?join=village&join=village.subsidyType`
        );
        let children = "village";
        res.data.forEach((town) => {
          town.village.forEach((village) => {
            village[children] = village.subsidyType;
          });
        });
        this.townToVillage = res.data;
      } else if (this.user.level == 2) {
        const res = await this.$http.get(
          `town/${this.user.town.id}?join=village&join=village.subsidyType`
        );
        let children = "village";
        res.data.village.forEach((village) => {
          village[children] = village.subsidyType;
        });
        this.townToVillage = res.data.village;
      } else if (this.user.level == 3) {
        const res = await this.$http.get(
          `village/${this.user.village.id}?join=subsidyType`
        );
        this.queryVillageAtt = res.data.subsidyType;
      }
    },
    setQuery() {
      if (this.user.level == 2) {
        this.queryForm.town = this.user.town.id;
        console.log(this.queryForm.town);
      } else if (this.user.level == 3) {
        this.queryForm.town = this.user.town.id;
        this.queryForm.village = this.user.village.id;
      }
    },
    townToVillageChange(att) {
      this.queryForm.town = att[0];
      this.queryForm.village = att[1] || "";
      this.queryForm.type = att[2] || "";
      this.fetchData();
    },
    villageToTypeChange(att) {
      this.queryForm.village = att[0];
      this.queryForm.type = att[1] || "";
      this.fetchData();
    },
    typeChange(att) {
      this.fetchData();
    },
    changeDataTimeRange() {
      this.fetchData();
    },
    actorChange() {
      this.fetchData();
    },
  },
};
</script>

<style>
.el-table .log-row {
  background: #f0f9eb;
}

.el-table .warn-row {
  background: oldlace;
}

.el-table .error-row {
  background: #f3c8c8;
}

.el-table .info-row {
  background: #7adad5;
}

.el-table .data-row {
  background: #dfc8f5;
}

.mr-5px {
  margin-right: 5px;
}
</style>